﻿using System.IO;
using System.Runtime.Serialization;
using System.Text;
using System.Xml;

namespace Snake
{
    public static class XmlUtility
    {
        public static string ToXmlString<T>(T obj)
        {
            var s = new DataContractSerializer(typeof(T));
            var ms = new MemoryStream();
            s.WriteObject(ms, obj);
            ms.Flush();
            return Encoding.UTF8.GetString(ms.GetBuffer());
        }

        public static T FromXml<T>(string xml)
        {
            var s = new DataContractSerializer(typeof(T));
            var ms = new MemoryStream(Encoding.UTF8.GetBytes(xml));
            return (T)s.ReadObject(ms);
        }

        public static void ToXml<T>(T obj, Stream stream)
        {
            var s = new DataContractSerializer(typeof(T));
            s.WriteObject(stream, obj);
            stream.Flush();
        }

        public static T FromXml<T>(Stream stream)
        {
            var s = new DataContractSerializer(typeof(T));
            return (T)s.ReadObject(stream);
        }

        public static void ToXmlBinary<T>(T obj, Stream stream)
        {
            var s = new DataContractSerializer(typeof(T));
            var writer = XmlDictionaryWriter.CreateBinaryWriter(stream);
            s.WriteObject(writer, obj);
            writer.Flush();
        }
        
        public static T FromXmlBinary<T>(Stream stream)
        {
            var s = new DataContractSerializer(typeof(T));
            var reader = XmlDictionaryReader.CreateBinaryReader(stream, new XmlDictionaryReaderQuotas());
            return (T)s.ReadObject(reader);
        }
    }
}